/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-04     LOJAM       the first version
 */



#include <rtthread.h>
#include <stdint.h>
#include <stddef.h>
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include "nimble/ble.h"
#include "host/ble_hs.h"
#include "services/gap/ble_svc_gap.h"
#include "ble_smarthome.h"

#ifdef BSP_USING_NIMBLE

static bool notify_state;
static uint16_t notify_conn_handle;

static const char *device_name = "Silicon_Smarthome";   //_Controller";

static int blehr_gap_event(struct ble_gap_event *event, void *arg);

static uint8_t smrthm_addr_type;

/* Sending notify data timer */
static struct ble_npl_callout blehr_tx_timer;

/* Variable to simulate heart beats */
static uint8_t heartrate = 90;

void nimble_port_run(void);
void nimble_port_init(void);
int ble_hci_rtthread_init(void);
void ble_svc_gap_init(void);
void ble_store_ram_init(void);
int smrthm_main(void);
void bb_init(void);
void bthw_get_heap_info(void **p_heap, uint16_t **p_heap_size, uint32_t *p_block_size);
typedef void (*nsmem_cb_init_func)(void *heap_buf, void *heap_size_buf, uint32_t mem_block_max);
#define nsmem_cb_init   ((nsmem_cb_init_func)0x84140)



/*
 * Enables advertising with parameters:
 *     o General discoverable mode
 *     o Undirected connectable mode
 */
static void blehr_advertise(void)
{
    struct ble_gap_adv_params adv_params;
    struct ble_hs_adv_fields fields;
    int rc;

    /*
     *  Set the advertisement data included in our advertisements:
     *     o Flags (indicates advertisement type and other general info)
     *     o Advertising tx power
     *     o Device name
     */
    memset(&fields, 0, sizeof(fields));

    /*
     * Advertise two flags:
     *      o Discoverability in forthcoming advertisement (general)
     *      o BLE-only (BR/EDR unsupported)
     */
    fields.flags = BLE_HS_ADV_F_DISC_GEN |
                    BLE_HS_ADV_F_BREDR_UNSUP;

    /*
     * Indicate that the TX power level field should be included; have the
     * stack fill this value automatically.  This is done by assigning the
     * special value BLE_HS_ADV_TX_PWR_LVL_AUTO.
     */
    fields.tx_pwr_lvl_is_present = 1;
    fields.tx_pwr_lvl = BLE_HS_ADV_TX_PWR_LVL_AUTO;

    fields.name = (uint8_t *)device_name;
    fields.name_len = strlen(device_name);
    fields.name_is_complete = 1;

    rc = ble_gap_adv_set_fields(&fields);
    if (rc != 0) {
        MODLOG_DFLT(ERROR, "error setting advertisement data; rc=%d\n", rc);
        return;
    }

    /* Begin advertising */
    memset(&adv_params, 0, sizeof(adv_params));
    adv_params.conn_mode = BLE_GAP_CONN_MODE_UND;
    adv_params.disc_mode = BLE_GAP_DISC_MODE_GEN;
    rc = ble_gap_adv_start(smrthm_addr_type, NULL, BLE_HS_FOREVER,
                           &adv_params, blehr_gap_event, NULL);
    if (rc != 0) {
        MODLOG_DFLT(ERROR, "error enabling advertisement; rc=%d\n", rc);
        return;
    }
}

static void smrthm_ble_tx_status_stop(void)
{
    ble_npl_callout_stop(&blehr_tx_timer);
}

/* Reset Smarthome measurment */
static void smrthm_ble_tx_reset(void)
{
    int rc;

    rc = ble_npl_callout_reset(&blehr_tx_timer, RT_TICK_PER_SECOND);
    assert(rc == 0);
}

/* This functions simulates heart beat and notifies it to the client */
static void smrthm_ble_tx_status(struct ble_npl_event *ev)
{
    static uint8_t smrthm_sta[2];
    int rc;
    struct os_mbuf *om;

    if (!notify_state) {
        smrthm_ble_tx_status_stop();
        heartrate = 90;
        return;
    }

    smrthm_sta[0] = 0x06; /* contact of a sensor */
    smrthm_sta[1] = heartrate; /* storing dummy data */

    /* Simulation of heart beats */
    heartrate++;
    if (heartrate == 160) {
        heartrate = 90;
    }

    om = ble_hs_mbuf_from_flat(smrthm_sta, sizeof(smrthm_sta));

    rc = ble_gattc_notify_custom(notify_conn_handle, smrthm_ctrl_handle, om);

    assert(rc == 0);
    smrthm_ble_tx_reset();
}

static int blehr_gap_event(struct ble_gap_event *event, void *arg)
{
    switch (event->type) {
    case BLE_GAP_EVENT_CONNECT:
        /* A new connection was established or a connection attempt failed */
        MODLOG_DFLT(INFO, "connection %s; status=%d\n",
                    event->connect.status == 0 ? "established" : "failed",
                    event->connect.status);

        if (event->connect.status != 0) {
            /* Connection failed; resume advertising */
            blehr_advertise();
        }
        break;

    case BLE_GAP_EVENT_DISCONNECT:
        MODLOG_DFLT(INFO, "disconnect; reason=%d\n", event->disconnect.reason);

        /* Connection terminated; resume advertising */
        blehr_advertise();
        break;

    case BLE_GAP_EVENT_ADV_COMPLETE:
        MODLOG_DFLT(INFO, "adv complete\n");
        blehr_advertise();
        break;

    case BLE_GAP_EVENT_SUBSCRIBE:
        MODLOG_DFLT(INFO, "subscribe event; cur_notify=%d\n value handle; "
                          "val_handle=%d\n",
                    event->subscribe.cur_notify, smrthm_ctrl_handle);
        if (event->subscribe.attr_handle == smrthm_ctrl_handle) {
            notify_state = event->subscribe.cur_notify;
            notify_conn_handle = event->subscribe.conn_handle;
            smrthm_ble_tx_reset();
        } else if (event->subscribe.attr_handle != smrthm_ctrl_handle) {
            notify_state = event->subscribe.cur_notify;
            notify_conn_handle = 0;
            smrthm_ble_tx_status_stop();
        }
        break;

    case BLE_GAP_EVENT_MTU:
        MODLOG_DFLT(INFO, "mtu update event; conn_handle=%d mtu=%d\n",
                    event->mtu.conn_handle,
                    event->mtu.value);
        break;

    }

    return 0;
}

static void smrthm_on_sync(void)
{
    int rc;

    /* Use privacy */
    rc = ble_hs_id_infer_auto(0, &smrthm_addr_type);
    assert(rc == 0);

    /* Begin advertising */
    blehr_advertise();
}



int smrthm_main(void)
{
    int rc;

    /* Initialize the NimBLE host configuration */
    ble_hs_cfg.sync_cb = smrthm_on_sync;

    ble_npl_callout_init(&blehr_tx_timer, nimble_port_get_dflt_eventq(),
                    smrthm_ble_tx_status, NULL);

    rc = gatt_svr_init();
    assert(rc == 0);

    /* Set the default device name */
    rc = ble_svc_gap_device_name_set(device_name);
    assert(rc == 0);

    return 0;
}

int btctrl_mem_init(void)
{
    void *heap_buf;
    uint16_t *heap_size_buf;
    uint32_t block_size;

    bthw_get_heap_info(&heap_buf, &heap_size_buf, &block_size);
    nsmem_cb_init(heap_buf, heap_size_buf, block_size);
    return 0;
}
INIT_BOARD_EXPORT(btctrl_mem_init);

static void ble_smarthome_thread_entry(void *param)
{
    bb_init();
    nimble_port_init();

    ble_hci_rtthread_init();
    ble_svc_gap_init();

    /* XXX Need to have template for store */
    ble_store_ram_init();

    smrthm_main();

    nimble_port_run();
}

static int ble_smarthome(void)
{
    rt_thread_t tid = rt_thread_create(
        "smarthome",
        ble_smarthome_thread_entry,
        RT_NULL,
        1024,
        15,
        1);

    if (tid != RT_NULL)
    {
        rt_thread_startup(tid);
    }
}

//MSH_CMD_EXPORT(ble_smarthome, ble_smarthome);
INIT_APP_EXPORT(ble_smarthome);
#endif
